home *** CD-ROM | disk | FTP | other *** search
/ Exame Informatica 139 / Exame Informatica 139.iso / Revista / Flash / Uniform Server / diskw / home / admin / www / phpMyBackupPro / functions.inc.php < prev    next >
Encoding:
PHP Script  |  2005-07-14  |  48.0 KB  |  1,228 lines

  1. <?php
  2. /*
  3.  +--------------------------------------------------------------------------+
  4.  | phpMyBackupPro                                                           |
  5.  +--------------------------------------------------------------------------+
  6.  | Copyright (c) 2004-2005 by Dirk Randhahn                                 |
  7.  | http://www.phpMyBackupPro.net                                            |
  8.  | version information can be found in definitions.php.                     |
  9.  |                                                                          |
  10.  | This program is free software; you can redistribute it and/or            |
  11.  | modify it under the terms of the GNU General Public License              |
  12.  | as published by the Free Software Foundation; either version 2           |
  13.  | of the License, or (at your option) any later version.                   |
  14.  |                                                                          |
  15.  | This program is distributed in the hope that it will be useful,          |
  16.  | but WITHOUT ANY WARRANTY; without even the implied warranty of           |
  17.  | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            |
  18.  | GNU General Public License for more details.                             |
  19.  |                                                                          |
  20.  | You should have received a copy of the GNU General Public License        |
  21.  | along with this program; if not, write to the Free Software              |
  22.  | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA.|
  23.  +--------------------------------------------------------------------------+
  24. */
  25.  
  26. // standard debug function
  27. function PMBP_debug($object) {
  28.     echo "<pre>";
  29.     print_r($object);
  30.     echo "</pre>";
  31. }
  32.  
  33.  
  34. // prints the basis html header in the $lang language with $scriptname scriptname
  35. function PMBP_print_header($scriptname) {
  36.     global $CONF;
  37.     global $_POST;
  38.     
  39.     if (!isset($CONF['stylesheet'])) $CONF['stylesheet']="standard";
  40.     echo "<!DOCTYPE HTML PUBLIC \"-//W3C/
  41.     /DTD HTML 4.01//EN\"
  42.    \"http://www.w3.org/TR/html4/loose.dtd\">
  43. <html".ARABIC_HTML.">
  44. <head>
  45. <title>phpMyBackupPro ".PMBP_VERSION."</title>
  46. <meta http-equiv=\"Content-Type\" content=\"text/html;charset=".BD_CHARSET_HTML."\">
  47. <meta name=\"robots\" content=\"noindex\">
  48. <meta name=\"robots\" content=\"nofollow\">
  49. <link rel=\"stylesheet\" href=\"".PMBP_STYLESHEET_DIR.$CONF['stylesheet'].".css\" type=\"text/css\">
  50. ";
  51.     readfile(PMBP_JAVASCRIPTS);
  52.     // define menue
  53.     $menu=array("index.php"=>F_START,"config.php"=>F_CONFIG,"import.php"=>F_IMPORT,"backup.php"=>F_BACKUP,"scheduled.php"=>F_SCHEDULE,"db_info.php"=>F_DB_INFO,"sql_query.php"=>F_SQL_QUERY);
  54.     $accesskeys=array("index.php"=>"m","config.php"=>"c","import.php"=>"i","backup.php"=>"b","scheduled.php"=>"s","db_info.php"=>"d","sql_query.php"=>"q","logout"=>"l","help"=>"h");
  55.     $simple_width=140;
  56.     $width=count($menu)*$simple_width;
  57.     
  58.     echo "</head>
  59. <body>
  60. <table width=\"".$width."\">
  61.  <colgroup>
  62.   <col span=\"".count($menu)."\" width=\"".$simple_width."\">
  63.  </colgroup>
  64.  <tr>
  65.   <th colspan=\"".count($menu)."\" class=\"active\" id=\"menu\">\n";
  66.   // print titel
  67.   echo "<div id=\"logo\">\n";
  68.   echo PMBP_image_tag("logo.png","phpMyBackupPro","phpMyBackupPro Homepage",PMBP_WEBSITE);
  69.   echo "  ".PMBP_VERSION."\n";
  70.   echo "</div>\n<div id=\"help\">\n";
  71.     // generate popup link for proper help file
  72.     if (!file_exists("./".PMBP_LANGUAGE_DIR.$CONF['lang']."_help.php")) echo PMBP_pop_up("./".PMBP_LANGUAGE_DIR."english_help.php?script=".$scriptname,PMBP_image_tag("help.gif","",F_HELP).F_HELP,"help");
  73.         else echo  PMBP_pop_up("./".PMBP_LANGUAGE_DIR.$CONF['lang']."_help.php?script=".$scriptname,PMBP_image_tag("help.gif","",F_HELP).F_HELP,"help");
  74.  
  75.     echo "\n</div>\n<div id=\"logout\">\n";
  76.     // print logout link if function is not disabled
  77.     if (!($CONF['no_login']=="1" && $CONF['login']=="0")) {
  78.         echo "<a href=\"login.php?logout=TRUE\" accesskey=\"l\">";
  79.         echo PMBP_image_tag("login.gif","",F_LOGOUT);
  80.         echo F_LOGOUT."</a>\n";
  81.     }
  82.     echo "\n</div>\n";
  83.     echo "  </th>\n";
  84.  
  85. // print selection for several sql servers
  86. if (count($CONF['sql_passwd_s']) && basename($_SERVER['SCRIPT_NAME'])!=="config.php" && !isset($_POST['period'])) {
  87.     echo " </tr>
  88.  <tr>
  89.   <th colspan=\"".count($menu)."\">
  90.   <form action=\"".basename($_SERVER['SCRIPT_NAME'])."\" method=\"POST\">
  91.   <span class=\"bold_left\">Select working SQL server:</span>
  92.   <select name=\"mysql_host\" onchange=\"submit()\">\n";
  93.     if ($CONF['sql_host']==$_SESSION['sql_host_org'] && $CONF['sql_user']==$_SESSION['sql_user_org']) echo "<option value=\"-1\" selected>".$_SESSION['sql_host_org']." (".$_SESSION['sql_user_org'].")</option>\n";
  94.         else echo "<option value=\"-1\">".$_SESSION['sql_host_org']." (".$_SESSION['sql_user_org'].")</option>\n";
  95.     for($i=0;$i<count($CONF['sql_passwd_s']);$i++) {
  96.  
  97.         if (isset($CONF['sql_host_s'])) {
  98.             if ($CONF['sql_host']==$CONF['sql_host_s'][$i] && $CONF['sql_user']==$CONF['sql_user_s'][$i]) echo "<option value=\"".$i."\" selected>".$CONF['sql_host_s'][$i]." (".$CONF['sql_user_s'][$i].")</option>\n";
  99.                 else echo "<option value=\"".$i."\">".$CONF['sql_host_s'][$i]." (".$CONF['sql_user_s'][$i].")</option>\n";
  100.         } else {
  101.             echo "<option value=\"".$i."\">".$CONF['sql_host_s'][$i]." (".$CONF['sql_user_s'][$i].")</option>\n";
  102.         }
  103.     }
  104.     echo "  </select></form>
  105.   </th>\n";
  106. }
  107.  
  108. echo " </tr>
  109.  <!-- MENU -->
  110.  <tr>\n";
  111.  
  112.     // generate menu
  113.     foreach($menu as $filename=>$title) {
  114.  
  115.         // print active link
  116.         if ($filename==$scriptname && $filename!="login.php?logout=TRUE" && $filename!="HELP") {
  117.             echo "  <th class=\"active\">\n   <a href=\"".$filename."\" accesskey=\"".$accesskeys[$filename]."\">".PMBP_image_tag(substr($filename,0,strpos($filename,".")).".gif","",$title).$title."</a>\n  </th>\n";
  118.  
  119.         // print lasting menu
  120.         } elseif ($filename!="login.php?logout=TRUE" && $filename!="HELP") {
  121.             echo "  <th>\n   <a href=\"".$filename."\" accesskey=\"".$accesskeys[$filename]."\">".PMBP_image_tag(substr($filename,0,strpos($filename,".")).".gif","",$title).$title."</a>\n  </th>\n";
  122.         }
  123.         
  124.     }
  125.  
  126.     echo " </tr>
  127. </table>
  128. <table width=\"".$width."\">
  129.  <colgroup>
  130.   <col width=\"20\">
  131.   <col width=\"*\">
  132.   <col width=\"20\">
  133.  </colgroup>
  134.  <tr>
  135.   <td>
  136.      
  137.   </td>
  138.   <td class=\"main\">
  139. <!-- HEADER END -->
  140. ";
  141. }
  142.  
  143.  
  144. // print basis html footer
  145. function PMBP_print_footer() {
  146.     echo "\n<!-- FOOTER -->
  147.   </td>
  148.   <td>
  149.      
  150.   </td>
  151.  </tr>
  152. </table>
  153. <table width=\"980\">
  154.  <tr>
  155.   <th colspan=\"7\" class=\"active\">\n";
  156.    printf(F_FOOTER,"<a href=\"".PMBP_WEBSITE."\">","</a>");
  157.    echo "\n</th>\n </tr>\n";
  158.  
  159.     $dontcare=array();
  160.     // do this only once per session
  161.     if (!isset($_SESSION['PMBP_VERSION'])) {
  162.         // check if there is a good internet connection. If it is, look for a newer version of phpMyBackupPro
  163.         @exec("ping -n 1 -w 500 -l 1 phpmybackup.sourceforge.net",$dontcare,$ping_res);
  164.         if (!$ping_res) {
  165.             @set_time_limit("3");
  166.             $last_vers=@file("http://phpmybackup.sourceforge.net/vers.php?v=".PMBP_VERSION);
  167.             if ($last_vers[0]==PMBP_VERSION) $_SESSION['PMBP_VERSION']=FALSE;
  168.                 else $_SESSION['PMBP_VERSION']=TRUE;
  169.         } else {
  170.             $_SESSION['PMBP_VERSION']=FALSE;
  171.         }
  172.     }
  173.  
  174.     // new version found, print hint
  175.     if ($_SESSION['PMBP_VERSION']) {
  176.         echo "\n <tr>
  177.   <td class=\"red\">
  178.     ";
  179.         printf(F_NOW_AVAILABLE,"<a href=\"".PMBP_WEBSITE."\">","</a>");
  180.         echo " !!!
  181.   </td>
  182.  </tr>\n";
  183.     }
  184.     
  185.     $tmp=phpversion();
  186.     $phpvers=$tmp[0].$tmp[1].$tmp[2];
  187.     if ($phpvers<4.3) echo "<tr><td>PHP ".$tmp." detected. It is not recommended to use phpMyBackupPro with PHP < PHP 4.3. You can disable this message if you want in functions.inc.php line ".__LINE__.".</td></tr>";
  188.  
  189.     echo "</table>
  190. </body>
  191. </html>
  192. ";
  193. }
  194.  
  195.  
  196. // prints html export form used on several pages
  197. function PMBP_print_export_form($dirs1=FALSE) {
  198.     global $CONF;
  199.     global $PMBP_SYS_VAR;
  200.     
  201.     echo "\n<table width=\"940\">\n";
  202.     echo "<tr>\n<td>\n";
  203.     echo F_SELECT_DB.":\n";
  204.     echo "</td>\n<td> </td>\n<td>";
  205.     echo F_COMMENTS.":";
  206.     echo "</td>\n</tr><tr>\n<td>\n";
  207.     echo "<select name=\"db[]\" multiple=\"multiple\" size=\"10\">\n";
  208.     if (!$con=@mysql_connect($CONF['sql_host'],$CONF['sql_user'],$CONF['sql_passwd']));
  209.  
  210.     // find the availabe compression methods and set which are disabled and which is selected
  211.     if (!@function_exists("gzopen") || !@function_exists("gzcompress")) $disable_gzip=" disabled"; else $disable_gzip="";
  212.  
  213.     $last_dbs=explode("|",$PMBP_SYS_VAR['F_dbs']);
  214.     if (count(PMBP_get_db_list())>0) {
  215.         foreach(PMBP_get_db_list() as $db) {
  216.             if(in_array($db, $last_dbs)) {
  217.                 echo "<option value=\"".$db."\" selected>".$db."</option>\n";
  218.             } else {
  219.                 echo "<option value=\"".$db."\">".$db."</option>\n";
  220.             }
  221.         }
  222.     } else {
  223.         echo "<option></option>\n";
  224.     }
  225.     echo "</select>\n<br>";
  226.     echo PMBP_set_select("backup","db[]","[".F_SELECT_ALL."]");
  227.     echo "\n</td>\n<td> </td>\n<td>\n";
  228.     echo "<textarea name=\"comments\" rows=\"9\" cols=\"80\">".$PMBP_SYS_VAR['F_comment']."</textarea>\n<br>";
  229.     if($PMBP_SYS_VAR['F_tables']) $checked="checked"; else $checked="";
  230.     echo "<input type=\"checkbox\" name=\"tables\" ".$checked.">".F_EX_TABLES." | ";
  231.     if($PMBP_SYS_VAR['F_data']) $checked="checked"; else $checked="";    
  232.     echo "<input type=\"checkbox\" name=\"data\" ".$checked.">".F_EX_DATA." | ";
  233.     if($PMBP_SYS_VAR['F_drop']) $checked="checked"; else $checked="";    
  234.     echo "<input type=\"checkbox\" name=\"drop\" ".$checked.">".F_EX_DROP." | ";
  235.  
  236.     $comp_off=$comp_gzip=$comp_zip="";
  237.     if($PMBP_SYS_VAR['F_compression']=="gzip" && !$disable_gzip) $comp_gzip=" selected";
  238.         elseif($PMBP_SYS_VAR['F_compression']=="zip") $comp_zip=" selected";
  239.             else $comp_off=" selected";
  240.             
  241.     echo F_EX_COMP."
  242. <select name=\"zip\">
  243. <option".$comp_off." value=\"\">".F_EX_OFF."</option>
  244. <option ".$comp_gzip." ".$disable_gzip." value=\"gzip\">".F_EX_GZIP."</option>
  245. <option".$comp_zip." value=\"zip\">".F_EX_ZIP."</option>
  246. </select>\n</td>\n</tr>\n</table>\n<p></p>\n";
  247.  
  248.     // show directory backup form
  249.     if ($CONF['dir_backup']) {
  250.         if (!is_array($dirs1) && $PMBP_SYS_VAR['dir_lists']>=1) $dirs1=PMBP_get_dirs("../");
  251.         
  252.         $last_dirs=explode("|",$PMBP_SYS_VAR['F_ftp_dirs']);
  253.  
  254.         echo "\n\n<table width=\"940\">\n";
  255.         echo "<tr>\n<td>\n";
  256.         echo EX_DIRS.":<br>(<a href=\"scheduled.php?update_dir_list=TRUE\">".PMBP_EXS_UPDATE_DIRS."</a>)<br>\n";
  257.         echo "</td>\n<td> </td>\n<td>\n";
  258.         echo EX_DIRS_MAN.":<br>\n";
  259.         echo "</td>\n</tr><tr>\n<td>";
  260.         echo "<select name='dirs[]' multiple=\"multiple\" size=\"9\">";
  261.         foreach($dirs1 as $value) {
  262.             if (in_array("../".$value, $last_dirs)) {            
  263.                 echo "<option value=\""."../".$value."\" selected>"."../".$value."</option>\n";
  264.             } else {
  265.                 echo "<option value=\""."../".$value."\">"."../".$value."</option>\n";            
  266.             }
  267.         }
  268.         echo "</select>\n";
  269.         echo "\n</td>\n<td> </td>\n<td>\n";
  270.         echo "<textarea rows=\"8\" cols=\"63\" name=\"man_dirs\">".$PMBP_SYS_VAR['F_ftp_dirs_2']."</textarea>";
  271.         echo "</td>\n</tr>\n</table>\n<p></p>\n";
  272.     }
  273. }
  274.  
  275.  
  276. // checks if settings on the export form where made and saves them
  277. function PMBP_save_export_settings() {
  278.     global $PMBP_SYS_VAR;
  279.  
  280.     // check if any settings have changed
  281.     if ($PMBP_SYS_VAR['F_data']!=$_POST['data'] OR $PMBP_SYS_VAR['F_tables']!=$_POST['tables'] OR
  282.     $PMBP_SYS_VAR['F_compression']!=$_POST['zip'] OR $PMBP_SYS_VAR['F_drop']!=$_POST['drop']) {            
  283.         $PMBP_SYS_VAR['F_data']=$_POST['data'];
  284.         $PMBP_SYS_VAR['F_tables']=$_POST['tables'];
  285.         $PMBP_SYS_VAR['F_compression']=$_POST['zip'];
  286.         $PMBP_SYS_VAR['F_drop']=$_POST['drop'];
  287.     }
  288.  
  289.     if (isset($_POST['db'])) {
  290.         if (is_array($_POST['db'])) {
  291.              if ($PMBP_SYS_VAR['F_dbs']!=implode("|",$_POST['db'])) {
  292.                  $PMBP_SYS_VAR['F_dbs']=implode("|",$_POST['db']);
  293.              }
  294.         } else {
  295.             $PMBP_SYS_VAR['F_dbs']="";
  296.         }
  297.     } else {
  298.         $PMBP_SYS_VAR['F_dbs']="";
  299.     }
  300.             
  301.      if ($PMBP_SYS_VAR['F_comment']!=$_POST['comments']) {
  302.         $PMBP_SYS_VAR['F_comment']=$_POST['comments'];
  303.     }
  304.  
  305.     if (isset($_POST['dirs'])) {
  306.          if ($PMBP_SYS_VAR['F_ftp_dirs']!=implode("|",$_POST['dirs'])) {
  307.              $PMBP_SYS_VAR['F_ftp_dirs']=implode("|",$_POST['dirs']);
  308.          }
  309.     } else {
  310.         $PMBP_SYS_VAR['F_ftp_dirs']="";
  311.     }
  312.  
  313.     if ($PMBP_SYS_VAR['F_ftp_dirs_2']!=$_POST['man_dirs']) {
  314.         $PMBP_SYS_VAR['F_ftp_dirs_2']=$_POST['man_dirs'];
  315.     }
  316.     
  317.     // update global_conf.php
  318.     PMBP_save_global_conf();
  319. }
  320.  
  321.  
  322. // generates image tag
  323. function PMBP_image_tag($image,$alt="",$title="",$link=""){
  324.     if (strpos($image,"/")==0) {
  325.         $image=PMBP_IMAGE_DIR.$image;
  326.         $size=getimagesize($image);
  327.     } else {
  328.         $size=getimagesize(PMBP_IMAGE_DIR.basename($image));
  329.     }
  330.     if ($link)
  331.         return "<a href=\"".$link."\"><img src=\"".$image."\" alt=\"".$alt."\" title=\"".$title."\" ".$size[3]."></a>";
  332.     else
  333.         return "<img src=\"".$image."\" alt=\"".$alt."\" title=\"".$title."\" ".$size[3].">";
  334. }
  335.  
  336.  
  337. // generates javascript 'select all in input select' link
  338. function PMBP_set_select($form,$select,$link){
  339.     return "<a href=\"\" onclick=\"setSelect('".$form."','".$select."'); return false;\">".$link."</a>";
  340. }
  341.  
  342.  
  343. // generates javascript PMBP_pop_up link
  344. function PMBP_pop_up($path,$link,$type){
  345.     return "<a href='javascript:popUp(\"".$path."\",\"".$type."\")'>".$link."</a>";
  346. }
  347.  
  348.  
  349. // generates event hanlders to change the border color in a td.list list
  350. function PMBP_change_color($color1,$color2){
  351.     return "onmouseout=\"changeColor(this, '".$color1."');\" onmouseover=\"changeColor(this, '".$color2."');\"";
  352. }
  353.  
  354.  
  355. // generates javascript confirm dialog
  356. function PMBP_confirm($text,$path,$link){
  357.     global $CONF;
  358.     switch ($CONF['confirm']) {
  359.         case 0: return "<a href='javascript:confirmClick(\"".$text."\",\"".$path."\")'>".$link."</a>";
  360.         case 1: {
  361.             if (strstr($path,"all") || strstr($path,"ALL")) return "<a href='javascript:confirmClick(\"".$text."\",\"".$path."\")'>".$link."</a>";
  362.                 else return "<a href=\"".$path."\">".$link."</a>";
  363.         }
  364.         case 2: {
  365.             if (strstr($path,"ALL")) return "<a href='javascript:confirmClick(\"".$text."\",\"".$path."\")'>".$link."</a>";
  366.                 else return "<a href=\"".$path."\">".$link."</a>";
  367.         }
  368.         case 3: return "<a href=\"".$path."\">".$link."</a>";
  369.     }
  370. }
  371.  
  372.  
  373. // generates a dump of $db database
  374. // $tables and $data set whether tables or data to backup. $comment sets the commment text
  375. // $drop and $zip tell if to include the drop table statement or dry to pack
  376. function PMBP_dump($db,$tables,$data,$drop,$zip,$comment) {
  377.     global $CONF;
  378.     global $PMBP_SYS_VAR;
  379.     $error=FALSE;
  380.     
  381.     // set max string size before writing to file
  382.     if (@ini_get("memory_limit")) $max_size=900000*ini_get("memory_limit");
  383.         else $max_size=$PMBP_SYS_VAR['memory_limit'];
  384.     
  385.     // set backupfile name
  386.     if ($zip=="gzip") $backupfile=$db.".".$time=time().".sql.gz";
  387.         elseif($zip=="zip") $backupfile=$db.".".($time=time()).".sql.zip";
  388.             else $backupfile=$db.".".$time=time().".sql";
  389.     $backupfile=PMBP_EXPORT_DIR.$backupfile;
  390.                     
  391.     if ($con=@mysql_connect($CONF['sql_host'],$CONF['sql_user'],$CONF['sql_passwd'])) {
  392.  
  393.         //create comment
  394.         $out="# MySQL dump of database '".$db."' on host '".$CONF['sql_host']."'\n";
  395.         $out.="# backup date and time: ".strftime($CONF['date'],$time)."\n";
  396.         $out.="# built by phpMyBackupPro ".PMBP_VERSION."\n";
  397.         $out.="# ".PMBP_WEBSITE."\n\n";
  398.  
  399.         // write users comment
  400.         if ($comment) {
  401.             $out.="# comment:\n";
  402.             $comment=preg_replace("'\n'","\n# ","# ".$comment);
  403.             foreach(explode("\n",$comment) as $line) $out.=$line."\n";
  404.             $out.="\n";
  405.         }
  406.  
  407.         // print "use database" but not if more than one db are available
  408.         if (count(PMBP_get_db_list())>1) {
  409.             $out.="CREATE DATABASE IF NOT EXISTS `".$db."`;\n\n";
  410.             $out.="USE `".$db."`;\n";
  411.         }
  412.         
  413.         // select db
  414.         @mysql_select_db($db);        
  415.         
  416.         // get auto_increment values and names of all tables
  417.         $res=mysql_query("show table status");
  418.         $all_tables=array();
  419.         while($row=mysql_fetch_array($res)) $all_tables[]=$row;
  420.  
  421.         // get table structures
  422.         foreach ($all_tables as $table) {
  423.             $res1=mysql_query("SHOW CREATE TABLE `".$table['Name']."`");
  424.             $tmp=mysql_fetch_array($res1);
  425.             $table_sql[$table['Name']]=$tmp["Create Table"];
  426.         }
  427.  
  428.         // find foreign keys
  429.         $fks=array();
  430.         if (isset($table_sql)) {
  431.             foreach($table_sql as $tablenme=>$table) {
  432.                 $tmp_table=$table;
  433.                  // save all tables, needed for creating this table in $fks
  434.                 while (($ref_pos=strpos($tmp_table," REFERENCES "))>0) {
  435.                     $tmp_table=substr($tmp_table,$ref_pos+12);
  436.                     $ref_pos=strpos($tmp_table,"(");
  437.                     $fks[$tablenme][]=substr($tmp_table,0,$ref_pos);
  438.                 }
  439.             }
  440.         }
  441.  
  442.         // order $all_tables
  443.         $all_tables=PMBP_order_sql_tables($all_tables,$fks);
  444.  
  445.         // as long as no error occurred
  446.         if (!$error) {
  447.             foreach ($all_tables as $row) {
  448.                 $tablename=$row['Name'];
  449.                 $auto_incr[$tablename]=$row['Auto_increment'];
  450.  
  451.                 // don't backup tables in $PMBP_SYS_VAR['except_tables']
  452.                 if (in_array($tablename,explode(",",$PMBP_SYS_VAR['except_tables'])))
  453.                     continue;
  454.                 
  455.                 $out.="\n\n";
  456.                 // export tables
  457.                 if ($tables) {
  458.                     $out.="### structure of table `".$tablename."` ###\n\n";
  459.                     if ($drop) $out.="DROP TABLE IF EXISTS `".$tablename."`;\n\n";
  460.                     $out.=$table_sql[$tablename];
  461.  
  462.                     // add auto_increment value
  463.                     if ($auto_incr[$tablename]) {
  464.                         $out.=" AUTO_INCREMENT=".$auto_incr[$tablename];
  465.                     }
  466.                     $out.=" ;";
  467.                 }
  468.                 $out.="\n\n\n";
  469.  
  470.                 // export data
  471.                 if ($data && !$error) {
  472.                     $out.="### data of table `".$tablename."` ###\n\n";
  473.  
  474.                     // check if field types are NULL or NOT NULL
  475.                     $res3=mysql_query("show columns from `".$tablename."`");
  476.  
  477.                     $res2=mysql_query("select * from `".$tablename."`");
  478.                     for ($j=0;$j<mysql_num_rows($res2);$j++){
  479.                         $out .= "insert into `".$tablename."` values (";
  480.                         $row2=mysql_fetch_row($res2);
  481.                         // run through each field
  482.                         for ($k=0;$k<$nf=mysql_num_fields($res2);$k++) {
  483.                             // identify null values and save them as null instead of ''
  484.                             if (is_null($row2[$k])) $out .="null"; else $out .="'".mysql_escape_string($row2[$k])."'";
  485.                             if ($k<($nf-1)) $out .=", ";
  486.                         }
  487.                         $out .=");\n";
  488.  
  489.                         // if saving is successful, then empty $out, else set error flag
  490.                         if (strlen($out)>$max_size && $zip!="zip") {
  491.                             if ($out=PMBP_save_to_file($backupfile,$zip,$out,"a")) $out=""; else $error=TRUE;
  492.                         }
  493.                     }
  494.  
  495.                 // an error occurred! Try to delete file and return error status
  496.                 } elseif ($error) {
  497.                     @unlink("./".PMBP_EXPORT_DIR.$backupfile);
  498.                     return FALSE;
  499.                 }
  500.  
  501.                 // if saving is successful, then empty $out, else set error flag
  502.                 if (strlen($out)>$max_size && $zip!="zip") {
  503.                     if ($out=PMBP_save_to_file($backupfile,$zip,$out,"a")) $out=""; else $error=TRUE;
  504.                 }
  505.             }
  506.             
  507.         // an error occurred! Try to delete file and return error status
  508.         } else {
  509.             @unlink("./".$backupfile);
  510.             return FALSE;
  511.         }
  512.  
  513.         if ($zip=="zip") $zip="zip".$time;
  514.         if ($backupfile=PMBP_save_to_file($backupfile,$zip,$out,"a")) {
  515.             return basename($backupfile);
  516.         } else {
  517.             @unlink("./".$backupfile);
  518.             return FALSE;
  519.         }
  520.     } else {
  521.         return "DB_ERROR";
  522.     }
  523. }
  524.  
  525.  
  526. // orders the tables in $tables according to the constraints in $fks
  527. // $fks musst be filled like this: $fks[tablename][0]=needed_table1; $fks[tablename][1]=needed_table2; ...
  528. function PMBP_order_sql_tables($tables,$fks) {
  529.     // do not order if no contraints exist
  530.     if (!count($fks)) return $tables;
  531.  
  532.     // order
  533.     $new_tables=array();
  534.     $existing=array();
  535.     $modified=TRUE;
  536.     while(count($tables) && $modified==TRUE) {
  537.         $modified=FALSE;
  538.         foreach($tables as $key=>$row) {
  539.             // delete from $tables and add to $new_tables
  540.             if (isset($fks[$row['Name']])) {
  541.                 foreach($fks[$row['Name']] as $needed) {
  542.                     // go to next table if not all needed tables exist in $existing
  543.                     if(!in_array($needed,$existing)) continue 2;
  544.                 }
  545.             }
  546.             
  547.             // delete from $tables and add to $new_tables
  548.             $existing[]=$row['Name'];
  549.             $new_tables[]=$row;
  550.             prev($tables);
  551.             unset($tables[$key]);
  552.             $modified=TRUE;
  553.         }
  554.     }
  555.  
  556.     if (count($tables)) {
  557.         // probably there are 'circles' in the constraints, bacause of that no proper backups can be created yet
  558.         // TODO: this will be fixed sometime later through using 'alter table' commands to add the constraints after generating the tables
  559.         // until now, just add the lasting tables to $new_tables, return them and print a warning
  560.         foreach($tables as $row) $new_tables[]=$row;
  561.         echo "<div class=\"red_left\">THIS DATABASE SEEMS TO CONTAIN 'RING CONSTRAINTS'. pMBP DOES NOT SUPPORT THEM. PROBABLY THE FOLLOWING BACKUP IS DEFECT!</div>";
  562.     }
  563.     return $new_tables;
  564. }
  565.  
  566.  
  567. // saves the string in $fileData to the file $backupfile as gz file or not ($zip)
  568. // returns backup file name if name has changed (zip), else TRUE. If saving failed, return value is FALSE
  569. function PMBP_save_to_file($backupfile,$zip,$fileData,$mode) {
  570.     if ($zip=="gzip") {
  571.         if ($zp=@gzopen("./".$backupfile,$mode."9")) {
  572.             @gzwrite($zp,$fileData);
  573.             @gzclose($zp);
  574.             return $backupfile;
  575.         } else {
  576.             return FALSE;
  577.         }
  578.         
  579.     // $zip contains the timestamp
  580.     } elseif (substr($zip,0,3)=="zip") {
  581.         $file_path=dirname($backupfile);
  582.         $backupfile=basename($backupfile);
  583.         
  584.         // based on zip.lib.php 2.2 from phpMyBackupAdmin
  585.         // offical zip format: http://www.pkware.com/appnote.txt
  586.         
  587.         // End of central directory record
  588.         $eof_ctrl_dir="\x50\x4b\x05\x06\x00\x00\x00\x00";
  589.  
  590.         // "local file header" segment
  591.         $unc_len=strlen($fileData);
  592.         $crc=crc32($fileData);
  593.         $zdata=gzcompress($fileData);
  594.  
  595.         // string needed for decoding (because of crc bug)
  596.         $name_suffix=substr($zdata,-4,4);
  597.         $name_suffix2="_";
  598.         for($i=0;$i<4;$i++) $name_suffix2.=sprintf("%03d",ord($name_suffix[$i]));
  599.         $backupfile=substr($backupfile,0,strlen($backupfile)-8).$name_suffix2.".sql.zip";
  600.         $name=substr($backupfile,0,strlen($backupfile)-4);
  601.  
  602.         // fix crc bug
  603.         $zdata=substr(substr($zdata,0,strlen($zdata)-4),2);
  604.         $c_len=strlen($zdata);
  605.  
  606.         // dos time
  607.         $timearray=getdate(substr($zip,3));
  608.         $dostime=(($timearray['year']-1980)<<25)|($timearray['mon']<<21)|($timearray['mday']<<16)|
  609.             ($timearray['hours']<<11)|($timearray['minutes']<<5)|($timearray['seconds']>>1);
  610.         $dtime=dechex($dostime);
  611.         $hexdtime="\x".$dtime[6].$dtime[7]."\x".$dtime[4].$dtime[5]."\x".$dtime[2].$dtime[3]."\x".$dtime[0].$dtime[1];
  612.         eval('$hexdtime="'.$hexdtime.'";');
  613.  
  614.         // ver needed to extract, gen purpose bit flag, compression method, last mod time and date
  615.         $sub1="\x14\x00"."\x00\x00"."\x08\x00".$hexdtime;
  616.  
  617.         // crc32, compressed filesize, uncompressed filesize
  618.         $sub2=pack('V',$crc).pack('V',$c_len).pack('V',$unc_len);
  619.         
  620.         $fr="\x50\x4b\x03\x04".$sub1.$sub2;
  621.         
  622.         // length of filename, extra field length
  623.         $fr.=pack('v',strlen($name)).pack('v',0);
  624.         $fr.=$name;
  625.  
  626.         // "file data" segment and "data descriptor" segment (optional but necessary if archive is not served as file)
  627.         $fr.=$zdata.$sub2;
  628.  
  629.         // now add to central directory record
  630.         $cdrec="\x50\x4b\x01\x02";
  631.         $cdrec.="\x00\x00";                // version made by
  632.         $cdrec.=$sub1.$sub2;
  633.         
  634.          // length of filename, extra field length, file comment length, disk number start, internal file attributes, external file attributes - 'archive' bit set, offset
  635.         $cdrec.=pack('v',strlen($name)).pack('v',0).pack('v',0).pack('v',0).pack('v',0).pack('V',32).pack('V',0);
  636.         $cdrec.=$name;
  637.  
  638.         // combine data
  639.         $fileData=$fr.$cdrec.$eof_ctrl_dir;
  640.         
  641.         // total # of entries "on this disk", total # of entries overall, size of central dir, offset to start of central dir, .zip file comment length
  642.         $fileData.=pack('v',1).pack('v',1).pack('V',strlen($cdrec)).pack('V',strlen($fr))."\x00\x00";
  643.                     
  644.         if ($zp=@fopen("./".$file_path."/".$backupfile,"w")) {
  645.             @fwrite($zp,$fileData);
  646.             @fclose($zp);
  647.             return $backupfile;
  648.         } else {
  649.             return FALSE;
  650.         }
  651.         
  652.     // uncompressed
  653.     } else {
  654.         if ($zp=@fopen("./".$backupfile,$mode)) {
  655.             @fwrite($zp,$fileData);
  656.             @fclose($zp);
  657.             return $backupfile;
  658.         } else {
  659.             return FALSE;
  660.         }
  661.     }
  662. }
  663.  
  664.  
  665. // updates the content in global_conf.php
  666. function PMBP_save_global_conf() {
  667.     global $CONF;
  668.     global $PMBP_SYS_VAR;
  669.  
  670.     // to ensure that all configuration settings are saved
  671.     @ignore_user_abort(TRUE);
  672.     
  673.     // create content for global.conf
  674.     $file="<?php\n\n// This file is automatically generated and modified by phpMyBackupPro ".PMBP_VERSION."\n\n";
  675.     foreach($CONF as $item=>$conf) {
  676.         // don't save multi server settings to gloabl_conf.php
  677.         if ($item=="sql_host_s" || $item=="sql_user_s" || $item=="sql_passwd_s" || $item=="sql_db_s") continue;
  678.  
  679.         // update $_SESSION['sql_host_org'] usw. if new sql data were entered on the config page
  680.         if (basename($_SERVER['SCRIPT_NAME'])=="config.php") {
  681.             $_SESSION['sql_host_org']=$CONF['sql_host'];
  682.             $_SESSION['sql_user_org']=$CONF['sql_user'];
  683.             $_SESSION['sql_passwd_org']=$CONF['sql_passwd'];
  684.             $_SESSION['sql_db_org']=$CONF['sql_db'];
  685.         }    
  686.         
  687.         // save current $CONF['sql_...'] values only if we use the multi server mode
  688.         if ($item=="sql_host" && count($CONF['sql_host_s'])) {
  689.             $file.="\$CONF['".$item."']=\"".$_SESSION['sql_host_org']."\";\n";
  690.         } elseif ($item=="sql_user" && count($CONF['sql_host_s'])) {
  691.             $file.="\$CONF['".$item."']=\"".$_SESSION['sql_user_org']."\";\n";
  692.         } elseif ($item=="sql_passwd" && count($CONF['sql_host_s'])) {
  693.             $file.="\$CONF['".$item."']=\"".$_SESSION['sql_passwd_org']."\";\n";
  694.         } elseif ($item=="sql_db" && count($CONF['sql_host_s'])) {
  695.             $file.="\$CONF['".$item."']=\"".$_SESSION['sql_db_org']."\";\n";
  696.         } else {
  697.             // save the current values for all other settings
  698.             $file.="\$CONF['".$item."']=\"".$conf."\";\n";
  699.         }
  700.     }
  701.  
  702.     // unset 'last_scheduled_' values in sys vars which no longer belong to an account
  703.     foreach($PMBP_SYS_VAR as $key=>$value) {
  704.         if (substr($key,0,15)=="last_scheduled_" && substr($key,15)>=count($CONF['sql_host_s'])) unset($PMBP_SYS_VAR[$key]);
  705.     }
  706.     
  707.     // add system variables    
  708.     $file.="\n";
  709.     foreach($PMBP_SYS_VAR as $item=>$sys_var) $file.="\$PMBP_SYS_VAR['".$item."']=\"".$sys_var."\";\n";
  710.     
  711.     $file.="\n?>";
  712.     
  713.     // save to file
  714.     return PMBP_save_to_file(PMBP_GLOBAL_CONF,FALSE,$file,"w");
  715. }
  716.  
  717.  
  718. // saves $files backup files on $server ftp server in $path path using $user username and $pass password
  719. function PMBP_ftp_store($files) {
  720.     global $CONF;
  721.     $out=FALSE;
  722.     
  723.     // try to connect to server using username and passwort
  724.     if (!$CONF['ftp_server']) {
  725.         $out.="<div class=\"red\">".C_WRONG_FTP."!</div>";
  726.     } elseif (!$conn_id=@ftp_connect($CONF['ftp_server'],$CONF['ftp_port'])) {
  727.         $out.="<div class=\"red\">".F_FTP_1." '".$CONF['ftp_server']."'!</div>";
  728.     } else {
  729.         if (!$login_result=@ftp_login($conn_id,$CONF['ftp_user'],$CONF['ftp_passwd'])) {
  730.             $out.="<div class=\"red\">".F_FTP_2." '".$CONF['ftp_user']."'.</div>";
  731.         } else {
  732.  
  733.             // succesfully connected
  734.             if ($CONF['ftp_pasv']) ftp_pasv($conn_id,TRUE); else ftp_pasv($conn_id,FALSE);
  735.             if (!$CONF['ftp_path']) $path="."; else $path=$CONF['ftp_path'];
  736.             
  737.             // upload the files
  738.             foreach($files as $filename) {
  739.                 $dest_file=$path."/".$filename;
  740.                 $source_file="./".PMBP_EXPORT_DIR.$filename;
  741.  
  742.                 // try three times to upload
  743.                 $check=FALSE;
  744.                 for($i=0;$i<3;$i++)
  745.                     if (!$check) $check=@ftp_put($conn_id,$dest_file,$source_file,FTP_BINARY);
  746.                 if (!$check) $out.="<div class=\"red\">".F_FTP_3.": '".$source_file."' -> '".$dest_file."'.</div>\n";
  747.                     else $out.="<div class=\"green\">".F_FTP_4." '".$dest_file."'.</div>\n";
  748.             }
  749.  
  750.             // close the FTP connection
  751.             if (@function_exists("ftp_close")) @ftp_close($conn_id);
  752.         }
  753.     }
  754.     return $out;
  755. }
  756.  
  757.  
  758. // send email with $attachments backup files to $email email using $sitename for sender and subject
  759. function PMBP_email_store($attachments,$backup_info) {
  760.     global $CONF;
  761.     $out=FALSE;
  762.     $lb="\n";
  763.     $all_emails=explode(",",$CONF['email']);
  764.  
  765.     // new mail script (since v.1.4)
  766.     $mailtext=F_MAIL_2." '".$CONF['sitename']."'.".$lb;
  767.     if ($backup_info['comp']=="gzip") $mailtext.=INF_COMP.": gzip".$lb;
  768.         elseif ($backup_info['comp']=="zip") $mailtext.=INF_COMP.": zip".$lb;
  769.             else $mailtext.=INF_COMP.": ".F_NO.$lb;
  770.     if ($backup_info['drop']) $mailtext.=INF_DROP.": ".F_YES.$lb; else $mailtext.=INF_DROP.": ".F_NO.$lb;
  771.     if ($backup_info['tables']) $mailtext.=INF_TABLES.": ".F_YES.$lb; else $mailtext.=INF_TABLES.": ".F_NO.$lb;
  772.     if ($backup_info['data']) $mailtext.=INF_DATA.": ".F_YES.$lb; else $mailtext.=INF_DATA.": ".F_NO.$lb;
  773.     $mailtext.=INF_COMMENT.":".$lb.$backup_info['comments'];
  774.     srand((double)microtime()*1000000);
  775.     $boundary="=_".md5(uniqid(rand()).microtime());
  776.     $parts[-1]="Content-Type: text/plain; charset=\"".BD_CHARSET_EMAIL."\"".$lb.$lb.$mailtext.$lb;
  777.     for ($i=0;$i<count($attachments);$i++) {
  778.         foreach (file(PMBP_EXPORT_DIR.$attachments[$i]) as $val) $bodies[$i].=$val;
  779.         $bodies[$i]=rtrim(chunk_split(base64_encode($bodies[$i]), 76, $lb)).$lb;
  780.         $parts[$i]="Content-Type: application/zip; name=\"".$attachments[$i].
  781.         "\"".$lb."Content-Transfer-Encoding: base64".$lb."Content-Disposition: attachment; filename=\"".$attachments[$i]."\"".$lb.$lb.$bodies[$i].$lb;
  782.     }
  783.  
  784.     $encoded['body']="--".$boundary.$lb.implode("--".$boundary.$lb,$parts)."--".$boundary."--".$lb.$lb;
  785.     $headers="From: phpMyBackupPro on ".$CONF['sitename']." <".$all_emails[0].">".$lb."Mime-Version: 1.0".$lb."Content-Type: multipart/mixed;".$lb."\tboundary=\"".$boundary."\"";
  786.  
  787.     // send to all every addresses
  788.     foreach($all_emails as $email) {
  789.         // verify email
  790.         if (!eregi("^\ *[Σ÷ⁿ─╓▄a-zA-Z0-9_-]+(\.[Σ÷ⁿ─╓▄a-zA-Z0-9\._-]+)*@([Σ÷ⁿ─╓▄a-zA-Z0-9-]+\.)+([a-z]{2,4})$",$email)) {
  791.             $out.="<div class=\"red\">".F_MAIL_1."</div>\n";
  792.             continue;
  793.         }
  794.     }
  795.     
  796.     // create subject
  797.     if (count($CONF['sql_host_s'])) {
  798.         $subject=F_MAIL_4." ".$CONF['sitename']." (".$CONF['sql_host'].", ".$CONF['sql_user'].")";
  799.     } else {
  800.         $subject=F_MAIL_4." ".$CONF['sitename'];
  801.     }
  802.  
  803.     // send mail
  804.     if (!@mail($CONF['email'],$subject,$encoded['body'],$headers)) $out.="<div class=\"red\">".F_MAIL_5.".</div>\n";
  805.         else $out.="<div class=\"green\">".F_MAIL_6." ".$CONF['email'].".</div>\n";
  806.     
  807.     return $out;
  808. }
  809.  
  810.  
  811. // returns present local backup files after deleting backups files 
  812. function PMBP_get_backup_files() {
  813.     global $CONF;
  814.     $delete_files=FALSE;
  815.     $all_files=FALSE;
  816.     $result_files=FALSE;
  817.     $handle=@opendir("./".PMBP_EXPORT_DIR);
  818.     $remove_time=time()-($CONF['del_time']*86400);
  819.     while ($file=@readdir($handle)) {
  820.         if ($file!="." && $file!=".." && preg_match("'\.sql|\.sql\.gz|\.sql\.zip'",$file)) {
  821.             
  822.             // don't delete if del_time is false
  823.             if ($CONF['del_time']) {
  824.                 if (PMBP_file_info("time",$file)<$remove_time) $delete_files[]=$file; else $all_files[]=$file;
  825.             } else {
  826.                 $all_files[]=$file;
  827.             }
  828.         }
  829.     }
  830.     
  831.     // sort descending
  832.     if (is_array($all_files)) rsort($all_files);
  833.  
  834.     // delete oldest backup files if there are to many for one db
  835.     if (is_array($all_files)) {
  836.         foreach($all_files as $file) {
  837.             if (!isset($counter[$db=PMBP_file_info("db","./".PMBP_EXPORT_DIR.$file)])) $counter[$db]=1; else $counter[$db]++;
  838.             if ($counter[$db]>$CONF['del_number']) $delete_files[]=$file; else $result_files[]=$file;
  839.         }
  840.     }
  841.  
  842.     // now delete the files
  843.     if ($delete_files) PMBP_delete_backup_files($delete_files);
  844.  
  845.     // sort ascending
  846.     if (is_array($result_files)) sort($result_files);
  847.     return $result_files;
  848. }
  849.  
  850.  
  851. // delete the file(s) in mixed $files from local export dir and remote ftp server
  852. function PMBP_delete_backup_files($files) {
  853.     global $CONF;
  854.     $out=FALSE;
  855.     if(!is_array($files)) $files=array($files);
  856.     foreach($files as $file) @unlink("./".PMBP_EXPORT_DIR.$file);
  857.     // find and delete all old files from the ftp server
  858.     if ($CONF['ftp_use'] && $CONF['ftp_del']) $out=PMBP_ftp_del();
  859.     return $out;
  860. }
  861.  
  862.  
  863. // deletes $files backup files from $server ftp server in $path path using $user username and $pass password
  864. function PMBP_ftp_del() {
  865.     global $CONF;
  866.     $out=FALSE;
  867.  
  868.     // try to connect to server using username and passwort
  869.     if (!$CONF['ftp_server']) {
  870.         $out.="<div class=\"red\">".C_WRONG_FTP."</div>";
  871.     } elseif (!$conn_id=@ftp_connect($CONF['ftp_server'],$CONF['ftp_port'])) {
  872.         $out.="<div class=\"red\">".F_FTP_1." '".$CONF['ftp_server']."'!</div>";
  873.     } else {
  874.         if (!$login_result=@ftp_login($conn_id,$CONF['ftp_user'],$CONF['ftp_passwd'])) {
  875.             $out.="<div class=\"red\">".F_FTP_2." '".$CONF['ftp_user']."'.</div>";
  876.         } else {
  877.  
  878.             // succesfully connected
  879.             if ($CONF['ftp_pasv']) ftp_pasv($conn_id,TRUE); else ftp_pasv($conn_id,FALSE);
  880.  
  881.             // get files in remote directory
  882.             if (!$CONF['ftp_path']) $path="."; else $path=$CONF['ftp_path'];
  883.             $remote_files=ftp_nlist($conn_id,$path);
  884.             
  885.             if (is_array($remote_files)) {
  886.                 // separate filename
  887.                 for($i=0;$i<count($remote_files);$i++)
  888.                     if (strrchr($remote_files[$i],"/")) $remote_files[$i]=substr(strrchr($remote_files[$i],"/"),1);
  889.             
  890.                 // don't delete if del_time is false
  891.                 if ($CONF['del_time']) {
  892.                     foreach($remote_files as $remote_file) {
  893.                         if (PMBP_file_info("time",$remote_file)<$remove_time) $delete_files[]=$remote_file; else $all_files[]=$remote_file;
  894.                     }
  895.                 } else {
  896.                     $all_files=$remote_files;
  897.                 }
  898.                 
  899.                 // sort descending
  900.                 if (is_array($all_files)) rsort($all_files);
  901.                 
  902.                 // delete oldest backup files if there are to many for one db
  903.                 if (is_array($all_files)) {
  904.                     foreach($all_files as $file) {
  905.                         $db=PMBP_file_info("db",$file);
  906.                         if (!isset($counter[$db])) $counter[$db]=1; else $counter[$db]++;
  907.                         if ($counter[$db]>$CONF['del_number']) $delete_files[]=$file; else $result_files[]=$file;
  908.                     }
  909.                 }        
  910.                         
  911.                 // delete the files in $delete_files
  912.                 if (is_array($delete_files)) {
  913.                     foreach($delete_files as $filename) {
  914.                         $dest_file=$path."/".$filename;
  915.     
  916.                         // try three times to delete
  917.                         $check=FALSE;
  918.                         for($i=0;$i<3;$i++) {
  919.                             if (!$check) $check=@ftp_delete($conn_id,$dest_file);
  920.                         }
  921.                         if (!$check) $out.="<div class=\"red\">".sprintf(F_FTP_5."</div>\n",$dest_file);
  922.                             else $out.="<div class=\"green\">".sprintf(F_FTP_6."</div>\n",$dest_file);
  923.                     }
  924.                 }
  925.             }
  926.  
  927.             // close the FTP connection
  928.             if (@function_exists("ftp_close")) @ftp_close($conn_id);
  929.         }
  930.     }
  931.     return $out;
  932. }
  933.  
  934.  
  935. // returns list of databases on $host host using $user user and $passwd password
  936. function PMBP_get_db_list() {
  937.     global $CONF;
  938.  
  939.     // if there is given the name of a single database
  940.     if ($CONF['sql_db']) {
  941.         @mysql_connect($CONF['sql_host'],$CONF['sql_user'],$CONF['sql_passwd']);
  942.         if (@mysql_select_db($CONF['sql_db'])) $dbs=array($CONF['sql_db']);
  943.             else $dbs=array();
  944.         return $dbs;
  945.     }
  946.     
  947.     // else try to get a list of all available databases on the server
  948.     $list=array();
  949.     @mysql_connect($CONF['sql_host'],$CONF['sql_user'],$CONF['sql_passwd']);
  950.     $db_list=@mysql_list_dbs();
  951.     while ($row=@mysql_fetch_array($db_list))
  952.         if (@mysql_select_db($row['Database'])) $list[]=$row['Database'];
  953.     return $list;
  954. }
  955.  
  956.  
  957. // in dependency on $mode different modes can be selected (see below)
  958. function PMBP_file_info($mode,$path) {
  959.     $filename=ereg_replace(".*/","",$path);
  960.     $parts=explode(".",$filename);
  961.     switch($mode) {
  962.     
  963.         // returns the name of the database a $path backup file belongs to
  964.         case "db":
  965.             return $parts[0];
  966.         break;
  967.  
  968.         // returns the creation timestamp $path backup file
  969.         case "time":
  970.             return $parts[1];
  971.         break;
  972.         
  973.         // returns "gz" if $path backup file is gziped
  974.         case "gzip":
  975.             if (isset($parts[3])) if ($parts[3]=="gz") return $parts[3];
  976.         break;
  977.         
  978.         // returns "zip" if $path backup file is ziped
  979.         case "zip":
  980.             if (isset($parts[3])) if ($parts[3]=="zip") return $parts[3];
  981.         break;
  982.         
  983.         // returns type of compression of $path backup file or no
  984.         case "comp":
  985.             if (PMBP_file_info("gzip",$path)) return "gzip"; elseif (PMBP_file_info("zip",$path)) return "zip"; else return F_NO;
  986.         break;
  987.  
  988.         // returns the size of $path backup file
  989.         case "size":
  990.             return filesize($path);
  991.         break;
  992.  
  993.         // returns yes if the backup file contains 'drop table if exists' or no if not
  994.         case "drop":
  995.             if (($comp=PMBP_file_info("comp",$path))=="gzip") $lines=PMBP_ungzip("lines",$path);
  996.                 elseif ($comp=="zip") $lines=PMBP_unzip("lines",$path);
  997.                     else $lines=file($path);
  998.             foreach($lines as $line){
  999.                 $line=trim($line);
  1000.                 if (strtolower(substr($line,0,20))=="drop table if exists") return F_YES; else $drop=F_NO;
  1001.             }
  1002.             return $drop;
  1003.  
  1004.         break;
  1005.         
  1006.         // returns yes if the $path backup files contains tables or no if not
  1007.         case "tables":
  1008.             if (($comp=PMBP_file_info("comp",$path))=="gzip") $lines=PMBP_ungzip("lines",$path);
  1009.                 elseif ($comp=="zip") $lines=PMBP_unzip("lines",$path);
  1010.                     else $lines=file($path);
  1011.             foreach($lines as $line){
  1012.                 $line=trim($line);
  1013.                 if (strtolower(substr($line,0,12))=="create table") return F_YES; else $table=F_NO;
  1014.             }
  1015.             return $table;
  1016.         break;
  1017.  
  1018.         // returns yes if the $path backup files contains data or no if not
  1019.         case "data":
  1020.             if (($comp=PMBP_file_info("comp",$path))=="gzip") $lines=PMBP_ungzip("lines",$path);
  1021.                 elseif ($comp=="zip") $lines=PMBP_unzip("lines",$path);
  1022.                     else $lines=file($path);
  1023.             foreach($lines as $line){
  1024.                 $line=trim($line);
  1025.                 if (strtolower(substr($line,0,6))=="insert") return F_YES; else $data=F_NO;
  1026.             }
  1027.             return $data;
  1028.         break;
  1029.         
  1030.         // returns the comment stored to the backup file
  1031.         case "comment":
  1032.             if (($comp=PMBP_file_info("comp",$path))=="gzip") $lines=PMBP_ungzip("lines",$path);
  1033.                 elseif ($comp=="zip") $lines=PMBP_unzip("lines",$path);
  1034.                     else $lines=file($path);
  1035.             foreach($lines as $line){
  1036.                 $line=trim($line);
  1037.                 if (isset($comment) && substr($line,0,1)=="#") $comment.=substr($line,2)."<br>";
  1038.                     elseif(isset($comment) && substr($line,0,1)!="#") return $comment;
  1039.                 if ($line=="# comment:") $comment=FALSE;
  1040.             }
  1041.             if (isset($comment)) return $comment; else return FALSE;
  1042.         break;
  1043.     }
  1044. }
  1045.  
  1046.  
  1047. // returns the content of the gziped $path backup file. use of $mode see below
  1048. function PMBP_ungzip($mode,$path) {
  1049.     $file_data=gzfile($path);
  1050.     // returns one string or an array of lines
  1051.     if ($mode!="lines") return implode("",$file_data); else return $file_data;
  1052. }
  1053.  
  1054.  
  1055. // returns the content of the ziped $path backup file. use of $mode see below
  1056. function PMBP_unzip($mode,$path,$org_name="") {
  1057.     $all=FALSE;
  1058.     $all=@implode("",@file($path));
  1059.  
  1060.     // set original name
  1061.     if (!$org_name) $org_name=$path;
  1062.  
  1063.     // convert path to name of ziped file
  1064.     $filename=basename($org_name);
  1065.     $filename=substr($filename,0,strlen($filename)-4);
  1066.     
  1067.     // compare filname in zip and filename from $_GET
  1068.     if(substr($all,30,strlen($filename))!=$filename) {
  1069.  
  1070.         // exit if names differ
  1071.         echo F_WRONG_FILE.".";
  1072.         exit;
  1073.     } else {
  1074.  
  1075.         // get the suffix of the filename in hex
  1076.         $crc_bugfix=substr(substr($filename,0,strlen($filename)-4),strlen($filename)-12-4);
  1077.         $suffix="";
  1078.  
  1079.         // convert hex to ascii
  1080.         for($i=0;$i<12;) $suffix.=chr($crc_bugfix[$i++].$crc_bugfix[$i++].$crc_bugfix[$i++]);
  1081.         
  1082.         // remove central directory information (we have always just one ziped file)
  1083.         $comp=substr($all,-(strlen($all)-30-strlen($filename)));
  1084.         $comp=substr($comp,0,(strlen($comp)-80-strlen($filename)));
  1085.  
  1086.         // fix the crc bugfix (see function save_to_file)
  1087.         $comp="x£".$comp.$suffix;
  1088.         $file_data=gzuncompress($comp);
  1089.     }
  1090.  
  1091.     // returns one string or an array of lines
  1092.     if ($mode!="lines") return $file_data; else return explode("\n",$file_data);
  1093. }
  1094.  
  1095.  
  1096. // determines the best size type for filesize $size and returns array('value'=xxx,'type'=yyy)
  1097. function PMBP_size_type($size) {
  1098.     $types=array("B","KB","MB","GB");
  1099.     for ($i=0; $size>1000; $i++,$size/=1024);
  1100.     $result['value']=round($size,2);
  1101.     $result['type']=$types[$i];
  1102.     return $result;
  1103. }
  1104.  
  1105.  
  1106. // get recursive directory list
  1107. function PMBP_get_dirs($dir,$renew=FALSE) {
  1108.     $dirs=FALSE;
  1109.     
  1110.     // renew date if the 'renew' link was clicked
  1111.     if(isset($_GET['update_dir_list'])) $renew=true;
  1112.     
  1113.     // return existing data
  1114.     if($renew) unset($_SESSION['file_system'][$dir]);    
  1115.     if(isset($_SESSION['file_system'][$dir])) return $_SESSION['file_system'][$dir];    
  1116.  
  1117.     // create directory list
  1118.     $dir_handle=@opendir($dir);
  1119.     while ($file=@readdir ($dir_handle)) {
  1120.         if ($file!="." && $file!="..") {
  1121.             if (@is_dir($dir.$file)) {
  1122.                 $dirs[]=$file."/";
  1123.                 $tmp=PMBP_get_dirs($dir.$file."/",TRUE);
  1124.                 if (is_array($tmp)) foreach($tmp as $value) $dirs[]=$file."/".$value;
  1125.             }
  1126.         }
  1127.     }
  1128.     $_SESSION['file_system'][$dir]=$dirs;
  1129.     return $dirs;
  1130. }
  1131.  
  1132.  
  1133. // get list of all files in directory
  1134. function PMBP_get_files($dir) {
  1135.     global $CONF;
  1136.     
  1137.     $dirs=array();
  1138.     $dir=trim($dir);
  1139.     if ($dir_handle=@opendir($dir)) {
  1140.         while (FALSE!==($file=readdir($dir_handle))) {
  1141.         if ($file!="." && $file!="..") {
  1142.                 if (!is_dir($dir.$file)) {
  1143.                 $dirs[]=$dir.$file;
  1144.                 // recursive listing of files
  1145.                 } elseif($CONF['dir_rec']) {
  1146.                     $tmp=PMBP_get_files($dir.$file."/");
  1147.                     if (is_array($tmp)) foreach($tmp as $value) $dirs[]=$value;
  1148.                 }
  1149.             }
  1150.         }
  1151.         @closedir($dir_handle);
  1152.     }
  1153.     return $dirs;
  1154. }
  1155.  
  1156.  
  1157. // transfer files $files to FPT servers dirs and create missing folders
  1158. function PMBP_save_FTP($files) {
  1159.     global $CONF;
  1160.     $out=FALSE;
  1161.  
  1162.     // try to connect to server using username and passwort
  1163.     if (!$CONF['ftp_server']) {
  1164.         $out.="<div class=\"red\">".C_WRONG_FTP."</div>";
  1165.     } elseif (!$conn_id=@ftp_connect($CONF['ftp_server'],$CONF['ftp_port'])) {
  1166.         $out.="<div class=\"red\">".F_FTP_1." '".$CONF['ftp_server']."'!</div>";
  1167.     } else {
  1168.         if (!$login_result=@ftp_login($conn_id,$CONF['ftp_user'],$CONF['ftp_passwd'])) {
  1169.             $out.="<div class=\"red\">".F_FTP_2." '".$CONF['ftp_user']."'.</div>";
  1170.         } else {
  1171.  
  1172.             // succesfully connected -> set passive and change to the right path
  1173.             if ($CONF['ftp_pasv']) ftp_pasv($conn_id,TRUE); else ftp_pasv($conn_id,FALSE);
  1174.             if (!$CONF['ftp_path']) $path="."; else $path=$CONF['ftp_path'];
  1175.             @ftp_chdir($conn_id,$path);
  1176.             
  1177.             // create all missing folders
  1178.             foreach($files as $filepath) {
  1179.                 if (trim($filepath)) {
  1180.                     $filepath=trim($filepath);
  1181.                     $folders=explode("/",$filepath);
  1182.                     $filename=array_pop($folders);
  1183.                     $deep=0;
  1184.                     $all_folders="";
  1185.                     foreach($folders as $folder) {
  1186.                         if ($folder != "." && $folder != "..") {
  1187.                             if (! @ftp_chdir($conn_id,$folder)) {
  1188.                                 @ftp_mkdir($conn_id,$folder);
  1189.                                 @ftp_chdir($conn_id,$folder);
  1190.                             }
  1191.                             $all_folders.=$folder."/";
  1192.                             $deep++;
  1193.                         }
  1194.                     }
  1195.                     
  1196.                     // change back to $path
  1197.                     $rel_path="";
  1198.                     for ($i=0;$i<$deep;$i++) $rel_path.="../";
  1199.                     @ftp_chdir($conn_id,$rel_path);
  1200.                 
  1201.                     // define the source and destination pathes
  1202.                     $dest_file=$all_folders.$filename;
  1203.                     $source_file="./".$filepath;
  1204.  
  1205.                     // try three times to upload
  1206.                     $check=FALSE;
  1207.                     for($i=0;$i<3;$i++) if (!$check) $check=@ftp_put($conn_id,$dest_file,$source_file,FTP_BINARY);
  1208.                     if (!$check) $out.="<div class=\"red\">".F_FTP_3.": '".$source_file."' -> '".$dest_file."'.</div>\n";
  1209.                         else $out.="<div class=\"green\">".F_FTP_4." '".$dest_file."'.</div>\n";
  1210.                 }
  1211.             }
  1212.  
  1213.             // close the FTP connection
  1214.             if (@function_exists("ftp_close")) @ftp_close($conn_id);
  1215.         }
  1216.     }
  1217.     return $out;
  1218. }
  1219.  
  1220.  
  1221. // login module
  1222. function PMBP_auth () {
  1223.     header("WWW-Authenticate: Basic realm=\"phpMyBackupPro\"");
  1224.     header("HTTP/1.0 401 Unauthorized");
  1225.     echo LI_MSG."\n";
  1226. }
  1227. ?>
  1228.